import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/model/cook_info_model.dart';
import 'package:flutter_douban/model/knowledge_model.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'mother_food_view.dart';
import 'mother_knowledge_view.dart';

class HomeMotherPage extends StatefulWidget {
  const HomeMotherPage({Key? key}) : super(key: key);

  @override
  _HomeMotherPageState createState() => _HomeMotherPageState();
}

class _HomeMotherPageState extends State<HomeMotherPage> {
  int _cate = 1;
  int _stage = 1;

  /// 食谱数组
  List<CookInfoModel> _cookList = CookInfoModelList([]).list;
  List<KnowledgeModel> _knowledgeList = KnowledgeModelList([]).list;

  late CookInfoModelList _foodInfoModelList;
  late KnowledgeModelList _zhishiInfoModelList;

  List _stageList = [
    {'name': '备孕期', 'id': '1'},
    {'name': '备早期', 'id': '2'},
    {'name': '备中期', 'id': '3'},
    {'name': '备晚期', 'id': '4'},
    {'name': '哺乳期', 'id': '5'},
    {'name': '6个月以下', 'id': '6'},
    {'name': '6-9个月', 'id': '7'},
    {'name': '10-12个月', 'id': '8'},
    {'name': '13-24个月', 'id': '9'},
    {'name': '2-5岁', 'id': '10'},
    {'name': '6-17岁', 'id': '11'},
  ];

  /// 获取数据
  Future _getMotherData({bool replace = true}) async {
    try {
      Map<String, dynamic> result =
          await HttpService.getMotherData(cate: _cate, stage: _stage);
      if (_cate == 1) {
        /// 食谱
        List list = result['list'];
        list.insert(0, {'n': result['stage_msg']});
        _foodInfoModelList = CookInfoModelList.fromJson(list);
      } else {
        /// 知识
        _zhishiInfoModelList = KnowledgeModelList.fromJson(result['list']);
      }
      if (_cate == 1) {
        _cookList = _foodInfoModelList.list;
        return _cookList;
      } else {
        _knowledgeList = _zhishiInfoModelList.list;
        return _knowledgeList;
      }
    } catch (e) {
      print(e.toString());
    } finally {}
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMotherData();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        /// 列表样式 随数据改变
        FutureBuilder(
          future: _getMotherData(),
          builder: (context, snapshot) {
            // 请求已结束
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                // 请求失败，显示错误
                return Text("Error: ${snapshot.error}");
              } else {
                Widget centerWigget;
                if (_cate == 1) {
                  centerWigget = MotherFoodView(
                    cookList: _cookList,
                  );
                } else {
                  centerWigget = MotherKnowledgeView(zhiList: _knowledgeList);
                }
                // 请求成功，显示数据
                return centerWigget;
              }
            } else {
              // 请求未结束，显示loading
              return StancePage();
            }
          },
        ),

        Positioned(top: 0, child: _topSelectView()),
        Positioned(
            top: 40,
            child: Container(
              padding: EdgeInsets.only(left: 10, right: 10),
              height: 40,
              width: MediaQuery.of(context).size.width,
              color: Colors.white,
              child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: _stageList.length,
                  shrinkWrap: true, //增加
                  itemBuilder: (BuildContext context, int index) {
                    return _tagWidget(_stageList[index]);
                  }),
            ))
      ],
    );
  }

  /// 头部选择view
  Widget _topSelectView() {
    return Container(
      height: 40,
      width: MediaQuery.of(context).size.width,
      color: Colors.white,
      child: Column(
        children: [
          Container(
            height: 1,
            width: MediaQuery.of(context).size.width,
            color: AppColors.line,
          ),
          Row(
            children: [
              InkWell(
                child: Container(
                  alignment: Alignment.center,
                  height: 38,
                  width: MediaQuery.of(context).size.width / 2,
                  color: Colors.white,
                  child: Text(
                    '母婴食谱',
                    style: TextStyle(
                        fontSize: 14,
                        fontWeight:
                            _cate == 1 ? FontWeight.bold : FontWeight.w400,
                        color: _cate == 1 ? AppColors.black : Colors.black54),
                  ),
                ),
                onTap: () {
                  setState(() {
                    _cate = 1;
                    _getMotherData();
                  });
                },
              ),
              InkWell(
                child: Container(
                  alignment: Alignment.center,
                  height: 38,
                  width: MediaQuery.of(context).size.width / 2,
                  color: Colors.white,
                  child: Text(
                    '母婴小知识',
                    style: TextStyle(
                        fontSize: 14,
                        fontWeight:
                            _cate == 2 ? FontWeight.bold : FontWeight.w400,
                        color: _cate == 2 ? AppColors.black : Colors.black54),
                  ),
                ),
                onTap: () {
                  setState(() {
                    _cate = 2;
                    _getMotherData();
                  });
                },
              ),
            ],
          ),
          Container(
            height: 1,
            width: MediaQuery.of(context).size.width,
            color: AppColors.line,
          ),
        ],
      ),
    );
  }

  /// 时间点选择

  Widget _tagWidget(Map tag) {
    return InkWell(
        onTap: () {
          setState(() {
            _stage = int.parse(tag['id']);
            _getMotherData();
          });
        },
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 0, horizontal: 8),
          margin: EdgeInsets.symmetric(vertical: 8, horizontal: 6),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: _stage.toString() == tag['id']
                ? AppColors.yellow
                : AppColors.line,
            borderRadius: BorderRadius.all(Radius.circular(40)),
            border: Border.all(width: 1, color: Colors.transparent),
          ),
          child: Text(
            tag['name'],
            style: TextStyle(
                fontWeight: _stage.toString() == tag['id']
                    ? FontWeight.bold
                    : FontWeight.w400,
                fontSize: 11,
                color: _stage.toString() == tag['id']
                    ? AppColors.black
                    : AppColors.qianTextColor),
          ),
        ));
  }
}
